import {
  Button,
  Form,
  FormItem,
  InputNumber,
  message,
  Modal,
  RadioButton,
  RadioGroup,
  Space,
  TypographyText
} from 'ant-design-vue'
import { fa, fi } from 'element-plus/lib/locale'
import moment from 'moment'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { omit } from 'xe-utils'

import { jindouGiftApi, rechargeApi } from '@/apis'
import { JindouGiftGoodsItem } from '@/apis/jindouGiftTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import jindouGift from '@/router/routes/jindouGift'
import { bus, optionsToMap } from '@/utils'
import { handlePrice } from '@/utils/bsshow'
import { couponTypeOptions } from '@/views/order/constants'

export default defineComponent({
  name: 'JdgGoodsManage',
  setup() {
    const showSetPriceDlg = ref(false)
    const optionGoodsItemCur = ref({} as any)
    const syncLoading = ref(false)

    const showSortDialog = ref(false)
    const dialogLoading = ref(false)
    const { showConfirm } = useDialog()
    const upDownStatusOptions = [
      { label: '下架', value: 0 },
      { label: '上架', value: 1 }
    ]
    const goodsPropertyOptions = [
      { label: '虚拟商品', value: 0 },
      { label: '实物', value: 1 }
    ]
    const goodsTypeOptions = [
      { label: 'APP优惠券', value: 0 },
      { label: '券包', value: 1 },
      { label: '礼购商品', value: 2 }
    ]
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'batchButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '商品名称',
              field: 'name',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              title: '状态',
              field: 'status',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: upDownStatusOptions
              }
            },
            {
              title: '商品类型',
              field: 'goodsType',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: goodsTypeOptions
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100,
          resizable: true
        },
        checkboxConfig: {
          showHeader: true,
          range: true
        },
        columns: [
          {
            type: 'checkbox',
            width: 50
          },
          {
            title: '商品ID',
            field: 'id'
          },
          {
            title: '排序',
            field: 'sort'
          },
          {
            title: '商品名称',
            field: 'name',
            width: 200
          },
          {
            title: '商品类型',
            field: 'goodsType',
            formatter: ({ cellValue }) => {
              return optionsToMap(goodsTypeOptions)[cellValue]
            }
          },
          {
            title: '商品属性',
            field: 'goodsProperty',
            formatter: ({ cellValue }) => {
              return optionsToMap(goodsPropertyOptions)[cellValue]
            }
          },
          {
            title: '市场价（元）',
            field: 'marketPrice'
          },
          {
            title: '销售价（元）',
            slots: {
              default: 'salePrice'
            }
          },
          {
            title: '总库存',
            field: 'stock'
          },
          {
            title: '总销量',
            field: 'saleNum'
          },
          {
            title: 'ERP状态',
            field: 'erpStatus',
            formatter: ({ cellValue }) => {
              return optionsToMap(upDownStatusOptions)[cellValue]
            }
          },
          {
            title: '状态',
            fixed: 'right',
            slots: {
              default: 'status'
            },
            width: 100
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 250
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await jindouGiftApi.getGoodsList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    onMounted(() => {
      bus.on('refreshJdgGoodsList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })

    //获取选中的项
    function getSelectedItems() {
      return tableRef.value.table?.getCheckboxRecords()
    }

    //上下架操作
    function handleUpDown(item, toUp: boolean) {
      let ids = [] as any[]
      if (item) {
        ids.push(item.id)
      } else {
        ids = getSelectedItems().map(item => {
          return item.id
        })
      }
      showConfirm({
        content: toUp
          ? `确认上架${item ? '该' : '这些'}商品？`
          : `确认下架${item ? '该' : '这些'}商品？`,
        onOk: async () => {
          try {
            await jindouGiftApi.upDownGoods(ids, toUp ? 1 : 0)
            tableRef.value.refresh()
          } catch (error) {}
        }
      })
    }

    const router = useRouter()

    //新增商品
    function addNewGoods() {
      router.push({
        name: 'JdgAddOrEditGoods'
      })
    }

    //编辑商品
    function handleEdit(item) {
      router.push({
        name: item.goodsType == 2 ? 'JdgEditGiftGoods' : 'JdgAddOrEditGoods',
        query: {
          id: item.id
        }
      })
    }

    //手动同步
    async function syncGoods() {
      try {
        syncLoading.value = true
        await jindouGiftApi.goodsSync()
        message.success('同步成功')
      } finally {
        syncLoading.value = false
      }
    }

    //设置排序
    function handleSort(item) {
      Object.assign(optionGoodsItemCur.value, item)
      showSortDialog.value = true
    }

    //设置排序确定
    async function dialogConfirm() {
      if (!optionGoodsItemCur.value.sort) {
        message.warn('请输入排序')
      }
      try {
        dialogLoading.value = true
        await jindouGiftApi.setGoodsSort(
          optionGoodsItemCur.value.id,
          optionGoodsItemCur.value.sort
        )

        showSortDialog.value = false
        tableRef.value.refresh()
      } finally {
        dialogLoading.value = false
      }
    }
    return {
      tableRef,
      tableConfig,
      showSetPriceDlg,
      optionGoodsItemCur,
      syncLoading,
      showSortDialog,
      dialogLoading,
      syncGoods,
      handleSort,
      addNewGoods,

      handleUpDown,
      handleEdit,
      getSelectedItems,
      dialogConfirm
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            batchButtons: () => (
              <Space>
                <Button
                  type="primary"
                  onClick={() => this.handleUpDown(null, true)}
                  disabled={
                    !this.getSelectedItems() ||
                    this.getSelectedItems().length == 0
                  }
                >
                  批量上架
                </Button>
                <Button
                  type="primary"
                  disabled={
                    !this.getSelectedItems() ||
                    this.getSelectedItems().length == 0
                  }
                  onClick={() => this.handleUpDown(null, false)}
                >
                  批量下架
                </Button>
                <Button type="primary" onClick={() => this.addNewGoods()}>
                  新增商品
                </Button>
                <Button
                  type="primary"
                  loading={this.syncLoading}
                  onClick={() => this.syncGoods()}
                >
                  手动同步
                </Button>
              </Space>
            ),

            status: ({ row }) => {
              return (
                <Space>
                  {row.status == 0 ? (
                    <TypographyText type="danger">下架</TypographyText>
                  ) : (
                    <TypographyText type="success">上架</TypographyText>
                  )}
                </Space>
              )
            },

            salePrice: ({ row }) => {
              return <Space>{handlePrice(row.salePrice, row.saleGold)}</Space>
            },
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleEdit(row)}
                >
                  编辑商品
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleUpDown(row, row.status === 0)}
                >
                  {row.status === 0 ? '上架' : '下架'}
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleSort(row)}
                >
                  设置排序
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.showSortDialog}
          width={600}
          confirmLoading={this.dialogLoading}
          title={'设置排序'}
          destroyOnClose
          onOk={this.dialogConfirm}
        >
          <Form labelCol={{ span: 4 }} style={{ marginTop: '15px' }}>
            <FormItem label={'排序'} required>
              <InputNumber
                placeholder={'请输入'}
                v-model:value={this.optionGoodsItemCur.sort}
                style={{ width: '300px' }}
                min={1}
                maxlength={4}
              />
              <p style={{ marginTop: '10px', color: '#888' }}>
                请输入大于等于1的整数，值越小排前面
              </p>
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
})
